using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace AvaAI批量点评系统.Services;

/// <summary>
/// 实时音频播放器 - 专门处理流式音频chunk的实时播放
/// 模拟官方Python代码中的stream.write(audio_np.tobytes())功能
/// </summary>
public class RealtimeAudioPlayer : IDisposable
{
    private readonly ConcurrentQueue<byte[]> _audioQueue = new();
    private readonly CancellationTokenSource _cancellationTokenSource = new();
    private readonly SemaphoreSlim _playbackSemaphore = new(1, 1);
    private bool _isPlaying = false;
    private int _chunkIndex = 0;
    
    public event EventHandler<string>? StatusChanged;

    /// <summary>
    /// 开始实时音频播放服务
    /// </summary>
    public async Task StartAsync()
    {
        if (_isPlaying)
            return;

        _isPlaying = true;
        StatusChanged?.Invoke(this, "🎵 实时音频播放器已启动");
        
        // 启动后台播放任务
        _ = Task.Run(PlaybackWorkerAsync, _cancellationTokenSource.Token);
    }

    /// <summary>
    /// 停止实时音频播放服务
    /// </summary>
    public async Task StopAsync()
    {
        if (!_isPlaying)
            return;

        _isPlaying = false;
        _cancellationTokenSource.Cancel();
        StatusChanged?.Invoke(this, "🔇 实时音频播放器已停止");
    }

    /// <summary>
    /// 添加音频块到播放队列（模拟官方Python的实时播放）
    /// </summary>
    /// <param name="audioChunk">音频数据块</param>
    public void EnqueueAudioChunk(byte[] audioChunk)
    {
        if (!_isPlaying || audioChunk == null || audioChunk.Length == 0)
            return;

        _audioQueue.Enqueue(audioChunk);
        _chunkIndex++;
        
        Console.WriteLine($"🎵 [队列] 音频块 {_chunkIndex} 已加入播放队列: {audioChunk.Length} 字节");
        StatusChanged?.Invoke(this, $"🎵 音频块 {_chunkIndex} 已排队播放");
    }

    /// <summary>
    /// 后台播放工作线程
    /// </summary>
    private async Task PlaybackWorkerAsync()
    {
        Console.WriteLine("🎵 [播放器] 后台播放线程已启动");
        
        while (!_cancellationTokenSource.Token.IsCancellationRequested)
        {
            try
            {
                if (_audioQueue.TryDequeue(out var audioChunk))
                {
                    await PlaySingleChunkAsync(audioChunk);
                }
                else
                {
                    // 队列为空，等待新的音频块
                    await Task.Delay(50, _cancellationTokenSource.Token);
                }
            }
            catch (OperationCanceledException)
            {
                break;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ [播放器] 播放错误: {ex.Message}");
                StatusChanged?.Invoke(this, $"❌ 播放错误: {ex.Message}");
            }
        }
        
        Console.WriteLine("🎵 [播放器] 后台播放线程已停止");
    }

    /// <summary>
    /// 播放单个音频块
    /// </summary>
    private async Task PlaySingleChunkAsync(byte[] audioChunk)
    {
        await _playbackSemaphore.WaitAsync(_cancellationTokenSource.Token);
        
        try
        {
            var chunkId = Interlocked.Increment(ref _chunkIndex);
            Console.WriteLine($"🎵 [播放] 开始播放音频块 {chunkId}: {audioChunk.Length} 字节");
            
            // 检查音频格式
            if (!IsValidWavData(audioChunk))
            {
                Console.WriteLine($"⚠️ [播放] 音频块 {chunkId} 不是有效的WAV格式，跳过");
                return;
            }

            // 使用临时文件播放音频块
            var success = await PlayChunkViaTemporaryFile(audioChunk, chunkId);
            
            if (success)
            {
                Console.WriteLine($"✅ [播放] 音频块 {chunkId} 播放完成");
                StatusChanged?.Invoke(this, $"✅ 音频块 {chunkId} 播放完成");
            }
            else
            {
                Console.WriteLine($"❌ [播放] 音频块 {chunkId} 播放失败");
                StatusChanged?.Invoke(this, $"❌ 音频块 {chunkId} 播放失败");
            }
        }
        finally
        {
            _playbackSemaphore.Release();
        }
    }

    /// <summary>
    /// 通过临时文件播放音频块
    /// </summary>
    private async Task<bool> PlayChunkViaTemporaryFile(byte[] audioChunk, int chunkId)
    {
        var tempFile = Path.GetTempFileName();
        var audioFile = Path.ChangeExtension(tempFile, ".wav");
        
        try
        {
            // 写入临时文件
            await File.WriteAllBytesAsync(audioFile, audioChunk, _cancellationTokenSource.Token);
            
            // 根据操作系统选择播放命令
            string command;
            string arguments;
            
            if (OperatingSystem.IsWindows())
            {
                // Windows: 使用PowerShell播放
                command = "powershell";
                arguments = $"-Command \"try {{ (New-Object Media.SoundPlayer '{audioFile}').PlaySync() }} catch {{ Write-Host 'PlaySync failed' }}\"";
            }
            else if (OperatingSystem.IsLinux())
            {
                // Linux: 使用aplay
                command = "aplay";
                arguments = $"-q \"{audioFile}\"";
            }
            else if (OperatingSystem.IsMacOS())
            {
                // macOS: 使用afplay
                command = "afplay";
                arguments = $"\"{audioFile}\"";
            }
            else
            {
                Console.WriteLine($"⚠️ [播放] 不支持的操作系统，跳过音频块 {chunkId}");
                return false;
            }
            
            // 启动播放进程
            var processInfo = new ProcessStartInfo
            {
                FileName = command,
                Arguments = arguments,
                UseShellExecute = false,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };
            
            using var process = Process.Start(processInfo);
            if (process != null)
            {
                // 等待播放完成，但不超过10秒
                var completed = await Task.Run(() => process.WaitForExit(10000), _cancellationTokenSource.Token);
                
                if (!completed && !process.HasExited)
                {
                    Console.WriteLine($"⚠️ [播放] 音频块 {chunkId} 播放超时，强制终止");
                    try
                    {
                        process.Kill();
                    }
                    catch
                    {
                        // 忽略Kill失败
                    }
                }
                
                return completed && process.ExitCode == 0;
            }
            
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ [播放] 音频块 {chunkId} 播放异常: {ex.Message}");
            return false;
        }
        finally
        {
            // 异步清理临时文件
            _ = Task.Run(async () =>
            {
                await Task.Delay(2000); // 等待播放完成
                try
                {
                    if (File.Exists(audioFile))
                        File.Delete(audioFile);
                    if (File.Exists(tempFile))
                        File.Delete(tempFile);
                }
                catch
                {
                    // 忽略清理错误
                }
            });
        }
    }

    /// <summary>
    /// 检查是否为有效的WAV数据
    /// </summary>
    private bool IsValidWavData(byte[] data)
    {
        if (data == null || data.Length < 44)
            return false;

        // 检查RIFF头
        var riffHeader = System.Text.Encoding.ASCII.GetString(data, 0, 4);
        if (riffHeader != "RIFF")
            return false;

        // 检查WAVE格式
        var waveHeader = System.Text.Encoding.ASCII.GetString(data, 8, 4);
        if (waveHeader != "WAVE")
            return false;

        return true;
    }

    /// <summary>
    /// 获取当前播放状态
    /// </summary>
    public bool IsPlaying => _isPlaying;

    /// <summary>
    /// 获取队列中的音频块数量
    /// </summary>
    public int QueueCount => _audioQueue.Count;

    public void Dispose()
    {
        _cancellationTokenSource.Cancel();
        _cancellationTokenSource.Dispose();
        _playbackSemaphore.Dispose();
    }
} 